package hu.gar.web.user.registration;

import hu.gar.common.service.RoleService;
import hu.gar.common.service.UserService;
import hu.gar.vo.RoleVO;
import hu.gar.vo.UserVO;
import hu.gar.web.util.CommonMessageUtil;

import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@ManagedBean(name = "registrationBean")
@ViewScoped
public class RegistrationBean implements Serializable {

	private static final long serialVersionUID = -395264689868721344L;

	@ManagedProperty("#{userService}")
	private UserService userService;

	@ManagedProperty("#{roleService}")
	private RoleService roleService;

	private UserVO regUserVO;

	private String password;

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPasswordAgain() {
		return passwordAgain;
	}

	public void setPasswordAgain(String passwordAgain) {
		this.passwordAgain = passwordAgain;
	}

	private String passwordAgain;

	@PostConstruct
	public void init() {
		setRegUserVO(new UserVO());
	}

	public void registration() {

		UserVO userVO = getUserService().findByName(regUserVO.getUsername());
		if (userVO != null) {

			CommonMessageUtil.addMessage(FacesMessage.SEVERITY_ERROR,
					"user_exits");

			return;
		}
		if (!password.equals(passwordAgain)) {

			CommonMessageUtil.addMessage(FacesMessage.SEVERITY_ERROR,
					"pasword_dont_equals");

			return;
		}
		try {
			BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
			regUserVO.setPassword(encoder.encode(password));
			UserVO vo = getUserService().addUser(regUserVO);

			RoleVO roleVO = getRoleService().getRoleByName("USER");
			getUserService().addRoleToUser(vo.getId(), roleVO.getId());

			CommonMessageUtil.addMessage(FacesMessage.SEVERITY_INFO, "succes");

		} catch (Exception e) {
			e.printStackTrace();
			CommonMessageUtil.addMessage(FacesMessage.SEVERITY_ERROR, "error");

		}

	}

	public UserVO getRegUserVO() {
		return regUserVO;
	}

	public void setRegUserVO(UserVO regUserVO) {
		this.regUserVO = regUserVO;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

}
